package com.hyj.springcloud.controller;

import com.hyj.springcloud.entities.CommonResult;
import com.hyj.springcloud.entities.Payment;
import com.hyj.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
//如果不想每次都写private  final Logger logger = LoggerFactory.getLogger(当前类名.class); 可以用注解@Slf4j;      lombok这么吊????
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;
    @Value("${server.port}")
    private String port;
    @Autowired
    private DiscoveryClient discoveryClient;


    //rest风格,建议anno加以区分.    localhost:8001/payment/create?serial=firstTest
    @PostMapping("/payment/create")
    //前后分离.统一用返回结果commonResult.
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        log.info("insert:::" + result);

        if (result > 0) {
            return new CommonResult(200, "succ", result);
        } else {
            return new CommonResult(444, "444");
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment result = paymentService.getPaymentById(id);
        log.info("insert:::" + result);

        if (null != result) {
            return new CommonResult(200, "succ+"+port, result);
        } else {
            return new CommonResult(444, "444");
        }
    }

    @GetMapping("/payment/discover")
    public Object discover() {
        //获取服务清单列表.
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            System.out.println("service = " + service);
            //对微服实例的封装.
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                System.out.println("instance.getHost() = " + instance.getHost());
                System.out.println("instance.getInstanceId() = " + instance.getInstanceId());
                System.out.println("instance.getUri() = " + instance.getUri());
            }
        }

        return this.discoveryClient;
    }

    /**
     * test LoadBalance
     */
    @GetMapping("/payment/lb")
    public String getLoadBalance() {
        return port;
    }
}
